<?php

namespace app\models\db;

use app\models\behaviors\TagBehavior;
use app\models\queries\ArticleQuery;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\Expression;
use creocoder\taggable\TaggableBehavior;
/**
 * This is the model class for table "{{%article}}".
 *
 * @property integer $id
 * @property integer $uid
 * @property integer $entityId
 * @property integer $categoryId
 * @property string $title
 * @property string $face
 * @property string $content
 * @property integer $addTime
 * @property integer $upTime
 * @property string $keyWord
 * @property integer $commentNum
 * @property integer $viewNum
 * @property integer $status
 * @property integer $isTop
 * @property string $statusDesc
 *
 * @property Category $category
 * @property Tag[] $tags
  * @property Comment[] $comments
 */
class Article extends \yii\db\ActiveRecord
{
    const STATUS_PUBLISHED = 1;
    const STATUS_NOT_PUBLISHED = 0;

    protected $statusDescArray = [
        self::STATUS_PUBLISHED => '已发布',
        self::STATUS_NOT_PUBLISHED => '未发布',
    ];

    /**
     * 获取状态描述
     * @return mixed
     */
    public function getStatusDesc()
    {
        return $this->statusDescArray[$this->status];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%article}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uid'], 'required'],
            [['uid', 'categoryId', 'addTime', 'upTime', 'commentNum', 'viewNum', 'status', 'isTop'], 'integer'],
            [['content'], 'string'],
            [['title', 'face', 'keyWord'], 'string', 'max' => 255],
            [['entityId'],'default','value'=>new Expression('UUID_SHORT()')],
            ['tagValues', 'safe'],
        ];
    }

    public function behaviors()
    {
        return [

            'taggable' => [
                'class' => TaggableBehavior::className(),
                // 'tagValuesAsArray' => false,
                'tagRelation' => 'taggables',
                // 'tagValueAttribute' => 'name',
                // 'tagFrequencyAttribute' => 'frequency',
            ],
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'addTime',
                'updatedAtAttribute' => 'upTime'
            ],
            [
                'class' => TagBehavior::className(),
            ],


        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'uid' => '用户ID',
            'entityId' => 'EntityId',
            'categoryId' => '分类表Id',
            'title' => '标题',
            'face' => '封面',
            'content' => '内容',
            'addTime' => '添加时间',
            'upTime' => '更新时间',
            'keyWord' => '关键字',
            'commentNum' => '评论数',
            'viewNum' => '阅读数',
            'status' => '状态',
            'isTop' => '是否置顶',
            'tagValue' => '关键词',
        ];
    }



    /**
     * @param null $categoryId
     * @return array||Article[]
     */
    public static function getHotsArticles($categoryId = null)
    {
        $hots = Article::find()
            ->joinWith('category')
            ->andWhere(['status' => self::STATUS_PUBLISHED])
            ->andWhere('viewNum >= 10')
            ->andFilterWhere(['categoryId' => $categoryId])
            ->orderBy('viewNum desc,id desc')
            ->limit(10)
            ->all();
        return $hots;
    }

    /**
     * @param null $categoryId
     * @return array||Article[]
     */
    public static function getRecentArticles($categoryId = null)
    {
        $recent = Article::find()
            ->andWhere(['status' => self::STATUS_PUBLISHED])
            ->andFilterWhere(['categoryId' => $categoryId])
            ->orderBy('addTime desc,id desc')
            ->limit(10)
            ->all();
        return $recent;
    }

    /**
     * 获取所属栏目
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(),['id'=>'categoryId']);
    }

    /**
     * 获取文章评论
     * @return ActiveQuery
     */
    public function getComments()
    {
        return $this->hasMany(Comment::className(),['articleId'=>'id'])->andWhere(['deleted'=>Comment::STATUS_ACTIVE,'referId'=>0]);
    }

    /**
     * 获取关键词
     * @return ActiveQuery
     */
    public function getTags()
    {
        return $this->hasMany(Tag::className(),['id'=>'tag_id'])->viaTable('{{%tag_has_article}}',['article_id'=>'id']);
    }

    public function getTaggables()
    {
        return $this->hasMany(Taggable::className(),['id'=>'tag_id'])->viaTable('{{%post_tag_assn}}',['post_id'=>'id']);
    }

    /**
     * @return object
     */
    public static function find()
    {
        return new ArticleQuery(get_called_class());
    }

    /**
     * @return array
     */
    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_ALL,
        ];
    }


}
